package com.sfac.springBoot.modules.common.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

/**
 * Description: MyBasicErrorController
 * @author JiangHu
 * @date 2022-07-12 14:46:24
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MyBasicErrorController implements ErrorController {

	@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
	public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
		HttpStatus status = getStatus(request);
		if (status == HttpStatus.NOT_FOUND) {
			return new ModelAndView(new RedirectView("/common/404"));
		} else  {
			return new ModelAndView(new RedirectView("/common/500")); 
		}
	}

	@RequestMapping
	public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<>();
		HttpStatus status = getStatus(request);
		if (status == HttpStatus.NOT_FOUND) {
			result.put("status", status.value());
			result.put("message", "没有找到");
			result.put("data", "/common/404");
			return new ResponseEntity<>(result, status);
		} else {
			result.put("status", status.value());
			result.put("message", "内部错误");
			result.put("data", "/common/500");
			return new ResponseEntity<>(result, status);
		}
	}
	
	public HttpStatus getStatus(HttpServletRequest request) {
		Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
		if (statusCode == null) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
		try {
			return HttpStatus.valueOf(statusCode);
		}
		catch (Exception ex) {
			return HttpStatus.INTERNAL_SERVER_ERROR;
		}
	}
}
